package modulos;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;

import auxiliary.Constants;
import auxiliary.Database;

public class PanelMensuales extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	ArrayList<ArrayList<String>> listOfMensuales, listOfMaquinaria,
			listOfProductos;
	Database db;
	ArrayList<JRadioButton> radiobuttons;
	ButtonGroup group;
	JPanel radioPanel, cards, backPanel, backPanel2, gridPanel, datePanel,
			topPanel, leftPanel, mostrarPanel;
	int currentButton, currentMonth, currentYear;
	JTable jt, confirmarjt;
	TableModelMensuales mtm;
	PanelMensuales panel;
	ArrayList<String> years;
	String[] months;
	boolean monthselected;
	JComboBox yearCombo, monthsCombo;
	ImageIcon imageicon,add,delete,redicon,greenicon,planicon;
	JLabel imagelabel;
	JButton mostrarButton;
	String[] array;

	public PanelMensuales() {

		// boolean monthselected = false;
		panel = this;
		db = new Database();
		
		mtm = new TableModelMensuales();
		//jt = new JTable(mtm);
		confirmarjt = new JTable(mtm);
		listOfMensuales = new ArrayList<ArrayList<String>>();
		listOfProductos = new ArrayList<ArrayList<String>>();

		currentMonth = Calendar.getInstance().get(Calendar.MONTH);
		currentYear = Calendar.getInstance().get(Calendar.YEAR);
		months = new String[] { "Ene", "Feb", "Mar", "Abr", "May", "Jun",
				"Jul", "Ago", "Sep", "Oct", "Nov", "Dic" };
		years = new ArrayList<String>();

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

		imageicon = new ImageIcon(image);
		//imagelabel = new JLabel(imageicon);
		
		imgURL = ClassLoader.getSystemResource("images/red.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		redicon = new ImageIcon(image);
		
		Image img = redicon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		redicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/green.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		greenicon = new ImageIcon(image);
		
		img = greenicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		greenicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/add.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		add = new ImageIcon(image);
		
		img = add.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		add = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/delete.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		delete = new ImageIcon(image);
		
		img = delete.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		delete = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/plan.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		planicon = new ImageIcon(image);
		
		img = planicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		planicon = new ImageIcon(newimg);

		

		for (int i = 0; i < 20; i++) {
			years.add(Integer.toString(2011 + i));
		}

		yearCombo = new JComboBox(Constants.singleArrayListToString(years));
		monthsCombo = new JComboBox(Constants
				.getStartWeek(String.valueOf((Integer
						.valueOf((String) yearCombo.getSelectedItem())))));

		yearCombo.addActionListener(this);
		confirmarjt.setEnabled(false);
		confirmarjt.setRowHeight(22);
		confirmarjt.getTableHeader().setReorderingAllowed(false);
		confirmarjt.getTableHeader().setResizingAllowed(false);
		confirmarjt.setBackground(new Color(227, 228, 250));
		confirmarjt.getTableHeader().setFont(new Font("Dialog", Font.BOLD, 14));

		JScrollPane jspconfirmar = new JScrollPane(confirmarjt);
		jspconfirmar.setPreferredSize(new Dimension(900, 400));

		JButton crearButton = new JButton("Crear",planicon);
		crearButton.setActionCommand(Constants.MENSUALES_CREAR);
		crearButton.addActionListener(this);

		mostrarButton = new JButton("Mostrar");
		mostrarButton.setActionCommand(Constants.MENSUALES_MOSTRAR);
		mostrarButton.addActionListener(this);


		JPanel buttonPanel3 = new JPanel();
		buttonPanel3.setLayout(new BoxLayout(buttonPanel3, BoxLayout.X_AXIS));

		buttonPanel3.add(Box.createHorizontalGlue());
		buttonPanel3.add(crearButton, BorderLayout.CENTER);
		buttonPanel3.add(Box.createHorizontalGlue());
		//buttonPanel3.add(new JLabel(imageicon), BorderLayout.EAST);


		topPanel = new JPanel(new BorderLayout());

		leftPanel = new JPanel(new BorderLayout());
		datePanel = new JPanel(new BorderLayout());
		mostrarPanel = new JPanel(new BorderLayout());

		leftPanel.add(datePanel, BorderLayout.CENTER);
		leftPanel.add(mostrarPanel, BorderLayout.EAST);

		topPanel.add(leftPanel, BorderLayout.EAST);

		datePanel.add(monthsCombo, BorderLayout.CENTER);
		datePanel.add(yearCombo, BorderLayout.EAST);

		leftPanel.add(mostrarButton, BorderLayout.EAST);

		cards = new JPanel(new CardLayout());
		backPanel = new JPanel(new BorderLayout());
		backPanel2 = new JPanel(new BorderLayout());

		String labelText = "<html><B>Por favor seleccione una combinacion Semana/A&ntilde;o "
				+ "para ver las necesidades de produccion para esa semana</B>";
		String labelText2 = "<html><FONT COLOR=RED><B>No se ha creado lista de produccion para la combinacion seleccionada</B></FONT>";
		JLabel textLabel = new JLabel(labelText, JLabel.CENTER);
		JLabel textLabel2 = new JLabel(labelText2, JLabel.CENTER);

		backPanel.add(textLabel, BorderLayout.CENTER);
		JPanel imagePanel = new JPanel(new BorderLayout());
		imagePanel.add(new JLabel(imageicon), BorderLayout.EAST);
		backPanel.add(imagePanel, BorderLayout.SOUTH);

		JPanel errorPanel = new JPanel(new BorderLayout());
	
		errorPanel.add(textLabel2,BorderLayout.CENTER);
		errorPanel.add(buttonPanel3,BorderLayout.SOUTH);
		
		backPanel2.add(errorPanel, BorderLayout.CENTER);
		imagePanel = new JPanel(new BorderLayout());
		imagePanel.add(new JLabel(imageicon), BorderLayout.EAST);
		backPanel2.add(imagePanel, BorderLayout.SOUTH);

		cards.add(backPanel, Constants.PlanLabel.PANEL_INICIAL.toString());
		cards.add(backPanel2, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
		cards.add(createPanel(), Constants.PlanLabel.GRID_PANEL.toString());

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(cards, BorderLayout.CENTER);
		// this.add(buttonPanel, BorderLayout.SOUTH);

		this.setVisible(true);

	}

	private void setColumnWidth() {

//	jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//	jt.getColumnModel().getColumn(0).setPreferredWidth(27);
//	jt.getColumnModel().getColumn(1).setPreferredWidth(150);
//	jt.getColumnModel().getColumn(2).setPreferredWidth(80);
//	jt.getColumnModel().getColumn(3).setPreferredWidth(150);
//	jt.getColumnModel().getColumn(4).setPreferredWidth(360);

		confirmarjt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		confirmarjt.getColumnModel().getColumn(0).setPreferredWidth(389);
		confirmarjt.getColumnModel().getColumn(1).setPreferredWidth(200);
		confirmarjt.getColumnModel().getColumn(2).setPreferredWidth(200);
		confirmarjt.getColumnModel().getColumn(3).setPreferredWidth(200);

	}

	JPanel createPanel() {

		array = ((String) monthsCombo.getSelectedItem()).split("/");

		listOfMensuales = db.retrieveMensuales(array[0], array[1], array[2]);

		radiobuttons = new ArrayList<JRadioButton>();

		for (Integer i = 0; i < listOfMensuales.size(); i++) {
			radiobuttons.add(new JRadioButton());
			radiobuttons.get(i).setSize(20, 20);
			radiobuttons.get(i).setActionCommand(i.toString());
			radiobuttons.get(i).addActionListener(this);
			radiobuttons.get(0).setSelected(true);
		}

		group = new ButtonGroup();
		radioPanel = new JPanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));

		for (int i = 0; i < listOfMensuales.size(); i++) {
			group.add(radiobuttons.get(i));
			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));
		}

		confirmarjt.setEnabled(false);
		confirmarjt.setRowHeight(22);
		confirmarjt.getTableHeader().setReorderingAllowed(false);
		confirmarjt.getTableHeader().setFont(new Font("Dialog", Font.BOLD, 14));

		JScrollPane jsp = new JScrollPane(confirmarjt);
		jsp.setPreferredSize(new Dimension(900, 450));

		JButton addbutton = new JButton("Agregar",add);
		addbutton.setActionCommand(Constants.MENSUALES_AGREGAR);
		addbutton.addActionListener(this);

		JButton removebutton = new JButton("Eliminar",delete);
		removebutton.setActionCommand(Constants.MENSUALES_ELIMINAR);
		removebutton.addActionListener(this);

		//JButton confirmarbutton = new JButton("Confirmar");
		//confirmarbutton.setActionCommand(Constants.MENSUALES_CONFIRMAR);
		//confirmarbutton.addActionListener(this);

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(addbutton, BorderLayout.WEST);
		buttonPanel.add(removebutton, BorderLayout.EAST);
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(new JLabel(imageicon), BorderLayout.EAST);
		
		JPanel gridPanel = new JPanel(new BorderLayout());

		gridPanel.add(jsp, BorderLayout.CENTER);
		gridPanel.add(radioPanel, BorderLayout.WEST);
		gridPanel.add(buttonPanel, BorderLayout.SOUTH);

		return gridPanel;
	}

	void addRadioButton() {
		Integer buttonindex = listOfMensuales.size() -1;

		radiobuttons.add(new JRadioButton());
		radiobuttons.get(buttonindex).setSize(23, 23);
		radiobuttons.get(buttonindex).setActionCommand(buttonindex.toString());
		radiobuttons.get(buttonindex).addActionListener(this);

		group.add(radiobuttons.get(buttonindex));
		

		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}

		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	void deleteRadioButton(int button) {
		final int curr = button;

		
		group.remove(radiobuttons.get(curr));
		radiobuttons.remove(curr);
		
		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	public void updateTable() {
		mtm.updateTable(array[0], array[1], array[2]);
		setColumnWidth();
	}

	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		// JButton button = (JButton) e.getSource();
		array = ((String) monthsCombo.getSelectedItem()).split("/");

		if (command == Constants.MENSUALES_MOSTRAR) {

			listOfMensuales = db
					.retrieveMensuales(array[0], array[1], array[2]);

			updateTable();

			cards.remove(2);
			cards.add(createPanel(), Constants.PlanLabel.GRID_PANEL.toString());

			if (listOfMensuales.size() != 0) {
				CardLayout cl = (CardLayout) (cards.getLayout());
				cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
			} else {
				CardLayout cl = (CardLayout) (cards.getLayout());
				cl.show(cards, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
			}

		} else if (command == Constants.MENSUALES_CREAR) {

			listOfMensuales = db
					.retrieveMensuales(array[0], array[1], array[2]);

			updateTable();

			cards.remove(2);
			cards.add(createPanel(), Constants.PlanLabel.GRID_PANEL.toString());
			CardLayout cl = (CardLayout) (cards.getLayout());
			cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());

		} else if (command == Constants.MENSUALES_AGREGAR) {

			String[] labels = { "Nombre", "Prioridad", "Unidades Meta Mes" };
			int[] widths = { 10, 15, 10 };
			String[] descs = { "Nombre", "Prioridad", "Unidades Meta Mes" };

			new AgregarMensual(labels, widths, descs, Constants
					.getParentFrame(this));

		} else if (command == Constants.MENSUALES_ELIMINAR) {

			String[][] allvalues = Constants.arrayListToString(listOfMensuales);

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));

			String[] values = list.toArray(new String[0]);

			db.deleteMensuales(values);

			listOfMensuales = db
					.retrieveMensuales(array[0], array[1], array[2]);

			updateTable();

			deleteRadioButton(currentButton);

			radioPanel.revalidate();
			radioPanel.repaint();

		} else if (command == Constants.MENSUALES_CONFIRMAR) {

			/*CardLayout cl = (CardLayout) (cards.getLayout());
			cl.show(cards, Constants.GRID_CONFIRMAR_PANEL);*/

		} else if (command == Constants.MENSUALES_MODIFICAR) {

			CardLayout cl = (CardLayout) (cards.getLayout());
			cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());

		} else if ("comboBoxChanged".equals(e.getActionCommand())) {
			////System.out.println("User has selected an item from the combo box.");
			monthsCombo = new JComboBox(Constants.getStartWeek(String
					.valueOf((Integer.valueOf((String) yearCombo
							.getSelectedItem())))));
			topPanel = new JPanel(new BorderLayout());

			leftPanel = new JPanel(new BorderLayout());
			datePanel = new JPanel(new BorderLayout());
			mostrarPanel = new JPanel(new BorderLayout());

			leftPanel.add(datePanel, BorderLayout.CENTER);
			leftPanel.add(mostrarPanel, BorderLayout.EAST);

			topPanel.add(leftPanel, BorderLayout.EAST);

			datePanel.add(monthsCombo, BorderLayout.CENTER);
			datePanel.add(yearCombo, BorderLayout.EAST);

			leftPanel.add(mostrarButton, BorderLayout.EAST);
			// topPanel

			this.removeAll();

			this.setLayout(new BorderLayout());
			this.add(topPanel, BorderLayout.NORTH);
			this.add(cards, BorderLayout.CENTER);
			// this.add(buttonPanel, BorderLayout.SOUTH);

			this.revalidate();
			this.repaint();
			this.setVisible(true);
		} else {
			currentButton = Integer.valueOf(e.getActionCommand());
		}

	}

	public class AgregarMensual extends JDialog implements ActionListener {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		JPanel form;
		JTextField[] fields;
		String[] productoIDs, prioridades;
		JDialog agregarFrame;

		// Database db;
		JComboBox productolist, prioridadlist;
		// FuncionarioPanel panel;
		AgregarMensual agregarmensual;

		public AgregarMensual(final String[] labels, final int[] widths,
				final String[] tips, JFrame parent) {
			super(parent, "Agregar Producto a Mes",
					Dialog.ModalityType.DOCUMENT_MODAL);

			agregarFrame = this;

			prioridades = new String[] { "Alta", "Media", "Baja" };
			agregarmensual = this;
			// db = new Database();
			// handler = new ButtonHandler();
			contentPane = getContentPane();
			form = new JPanel(new BorderLayout());
			listOfProductos = db.retrieveProductos();

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));

			// JPanel listform = new JPanel(new BorderLayout());

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Produccion Deseada");
			form.setBorder(border);

			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));

			fieldPanel.setBorder(grayborder);

			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel);

			fields = new JTextField[labels.length];

			for (int i = 0; i < labels.length; i++) {
				fields[i] = new JTextField();
				if (i < tips.length)
					fields[i].setToolTipText(tips[i]);
				if (i < widths.length)
					fields[i].setColumns(widths[i]);

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				labelPanel.add(lab);

				if (i == 0) {
					productolist = new JComboBox();

					JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
					productolist = new JComboBox(Constants
							.arrayListToStringSelect(listOfProductos, 1, 2));
					productoIDs = Constants.arrayListToStringSelect(
							listOfProductos, 0, 1);
					p.add(productolist);
					fieldPanel.add(p);
				} else if (i == 1) {
					prioridadlist = new JComboBox();

					JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
					prioridadlist = new JComboBox(prioridades);
					p.add(prioridadlist);
					fieldPanel.add(p);
				} else {
					JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
					p.add(fields[i]);
					fieldPanel.add(p);
				}
			}

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.MENSUALES_AGREGAR_CANCELAR);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.MENSUALES_AGREGAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);
			
			contentPane.add(form, BorderLayout.NORTH);
			// contentPane.add(listform, BorderLayout.LINE_END);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);
			pack();

			setVisible(true);
		}

		public void actionPerformed(ActionEvent e) {

			ArrayList<String> mensualData = new ArrayList<String>();

			String command = e.getActionCommand();

			if (command == Constants.MENSUALES_AGREGAR_CONFIRMACION) {

				boolean validnumber = true;

				try {
					Integer.parseInt(fields[2].getText());
					// validnumber = true;
				} catch (Exception exp) {

					validnumber = false;
				}

				if (validnumber) {

					mensualData
							.add(productoIDs[productolist.getSelectedIndex()]);
					mensualData.add(Integer.toString(prioridadlist
							.getSelectedIndex()));
					mensualData.add(fields[2].getText());

					// TODO add array

					mensualData.add(array[0]);
					mensualData.add(array[1]);
					mensualData.add(array[2]);
					mensualData.add(fields[2].getText());

					db.insertMensuales(mensualData);

					String[] array = ((String) monthsCombo.getSelectedItem())
							.split("/");
					listOfMensuales = db.retrieveMensuales(array[0], array[1],
							array[2]);

					updateTable();
					addRadioButton();
					radioPanel.revalidate();
					agregarFrame.dispose();
					setColumnWidth();

				} else {
					JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validnumber ? ""
													: "- Ingrese un numero valido para unidades a producir en mes\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
			}else if (command == Constants.MENSUALES_AGREGAR_CANCELAR) {
				agregarFrame.dispose();
			}
		}
	}
}
